package com.sky.controller;

import com.sky.dto.OrderPayDTO;
import com.sky.dto.OrderRefundDTO;
import com.sky.entity.User;
import com.sky.mapper.UserMapper;
import com.sky.service.PayService;
import com.sky.vo.PayVO;
import com.sky.result.Result;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/admin/pay")
@Api(tags = "支付相关接口")
@Slf4j
public class PayController {

    @Autowired
    private PayService payService;
    
    @Autowired
    private UserMapper userMapper;  // 添加 UserMapper

    @PostMapping("/payment")
    @ApiOperation("支付订单")
    public Result<PayVO> payment(@RequestBody OrderPayDTO orderPayDTO) {
        log.info("支付订单：{}", orderPayDTO);
        Long userId = orderPayDTO.getUserId();
        User user = userMapper.getById(userId);
        if (user == null) {
            return Result.error("用户不存在");
        }
        
        // 传入订单号进行支付
        PayVO payVO = payService.payment(orderPayDTO.getOrderId().toString(), user.getOpenid());
        return Result.success(payVO);
    }

    @PostMapping("/notify")
    @ApiOperation("支付回调")
    public Result<String> payNotify(@RequestBody String notifyData) {
        log.info("支付回调：{}", notifyData);
        payService.paySuccess(notifyData);
        return Result.success();
    }

    @PostMapping("/refund")
    @ApiOperation("订单退款")
    public Result<String> refund(@RequestBody OrderRefundDTO refundDTO) {
        log.info("接收到的退款请求数据：{}", refundDTO);
        log.info("退款金额：{}", refundDTO.getRefundAmount());
        
        try {
            boolean result = payService.refund(
                refundDTO.getOrderId().toString(),
                refundDTO.getRefundAmount(), // 此处类型已匹配
                refundDTO.getRefundReason()
            );
            return result ? Result.success() : Result.error("退款失败");
        } catch (Exception e) {
            log.error("退款异常", e);
            return Result.error("退款异常：" + e.getMessage());
        }
    }
}